package com.siwei.mes.service.laboratory.factory.material.cement;

import com.alibaba.fastjson.JSONObject;
import com.siwei.mes.common.util.JsonUtils;
import com.siwei.mes.common.util.NullUtils;
import com.siwei.mes.entity.experiment.CheckBatchConfig;
import com.siwei.mes.entity.experiment.Experiment;
import com.siwei.mes.entity.experiment.ExperimentDetail;
import com.siwei.mes.entity.experiment.cement.CementXd;
import com.siwei.mes.entity.laboratory.DataDefaultUc;
import com.siwei.mes.entity.laboratory.cement.DataSnXd;
import com.siwei.mes.entity.system.TestProjectInfo;
import com.siwei.mes.entity.system.TestProjectSpecConfig;
import com.siwei.mes.enums.TestProjectEnum;
import com.siwei.mes.mapper.experiment.ExperimentDetailMapper;
import com.siwei.mes.mapper.laboratory.CementLaboratoryMapper;
import com.siwei.mes.mapper.laboratory.UploadLaboratoryMapper;
import com.siwei.mes.service.laboratory.factory.LaboratoryAbstractService;
import com.siwei.mes.service.laboratory.factory.entity.LaboratoryDownloadVo;
import com.siwei.mes.service.laboratory.factory.material.MaterialLaboratoryFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 水泥-细度
 *
 * @Description: 水泥-细度
 * @Version: 1.0
 * @author: mlchen
 * @date: 2025/3/29 17:21
 */
@Service
public class CementXdFactory extends LaboratoryAbstractService implements MaterialLaboratoryFactory {
    private static final Logger log = LoggerFactory.getLogger("laboratory");

    @Resource
    private CementLaboratoryMapper cementLaboratoryMapper;
    @Resource
    private UploadLaboratoryMapper uploadLaboratoryMapper;
    @Resource
    private ExperimentDetailMapper experimentDetailMapper;

    private final TestProjectEnum testProjectEnum = TestProjectEnum.CEMENT_PARAM_XD;

    @Override
    public void processUpload(JSONObject objJson, String sampleNo, Experiment experiment, List<CheckBatchConfig> batchConfigList, List<TestProjectInfo> testProjectInfoList, List<TestProjectSpecConfig> testProjectSpecConfigList, ExperimentDetail detail, String samId) {
        log.info("开始上传到协会数据库：【水泥-{}】", testProjectEnum.getName());
        CementXd cementXd = JsonUtils.getObject(objJson, CementXd.class);

        if (cementXd == null) {
            log.info("水泥-【{}】数据为空，跳过上传！objJson：{}", testProjectEnum.getName(), objJson);
            return;
        }

        DataSnXd dataSnXd = new DataSnXd();

        dataSnXd.setS11(NullUtils.ifNull(cementXd.getPjz()));
        dataSnXd.setS10(NullUtils.ifNull(cementXd.getXzxs()));
        dataSnXd.setConclusion(NullUtils.ifNull(cementXd.getSfhg()));
        dataSnXd.setSt1(NullUtils.ifNull(cementXd.getSt1()));
        int con = 1;
        for (CementXd.Fysff fysff : cementXd.getFysff()) {
            if (con == 1) {
                dataSnXd.setS1(NullUtils.ifNull(fysff.getClz()));
                dataSnXd.setS2(NullUtils.ifNull(fysff.getSyl()));
                dataSnXd.setS3(NullUtils.ifNull(fysff.getSylv()));
            } else if (con == 2) {
                dataSnXd.setS4(NullUtils.ifNull(fysff.getClz()));
                dataSnXd.setS5(NullUtils.ifNull(fysff.getSyl()));
                dataSnXd.setS6(NullUtils.ifNull(fysff.getSylv()));
            } else if (con == 3) {
                dataSnXd.setS7(NullUtils.ifNull(fysff.getClz()));
                dataSnXd.setS8(NullUtils.ifNull(fysff.getSyl()));
                dataSnXd.setS9(NullUtils.ifNull(fysff.getSylv()));
            }
            con++;
        }

        dataSnXd.setFangKongShaiGuiGe(cementXd.getFksgg());//默认写死80


        //设置公共属性
        super.setCommonProperties(sampleNo, experiment, dataSnXd, "水泥", cementXd.getJcrq(), detail);

        //根据样品编码查询水泥细度
        DataSnXd data_jgcl_sn_bzcdnjsjBySampleNo = cementLaboratoryMapper.findDATA_JGCL_SN_XD_SXFBySampleNo(sampleNo);
        //查询没值说明需要  新增水泥标准稠度与初凝时间
        if (data_jgcl_sn_bzcdnjsjBySampleNo == null) {
            cementLaboratoryMapper.addDATA_JGCL_SN_XD_SXF(dataSnXd);
        } else {
            //修改水泥标准稠度与初凝时间
            cementLaboratoryMapper.updateDATA_JGCL_SN_XD_SXF(dataSnXd);
        }


        //赋值dateDefalutUC
        //存储协会需要做的项目集合
        Set<String> set = new HashSet<>();

        for (TestProjectInfo testProjectInfo : testProjectInfoList) {
            if (detail.getTestProjectCode() != null && testProjectInfo.getTestCode() != null && testProjectInfo.getTestCode().equals(detail.getTestProjectCode())) {
                if (testProjectInfo.getParameterName() != null && !testProjectInfo.getParameterName().isEmpty()) {
                    //添加进协会需要做的项目集合
                    set.addAll(Arrays.asList(testProjectInfo.getParameterName().split(",")));
                }
            }
        }

        for (String str : set) {
            DataDefaultUc defaultUc = new DataDefaultUc();

            Map<String, Object> itemParameter = uploadLaboratoryMapper.findItemParameter(str, samId);

            if (itemParameter == null || itemParameter.get("ParameterID") == null) {
                log.error("未查询到对应的材料：value = " + str + "SampleID =" + samId);
                continue;
            }
            String parameterID = itemParameter.get("ParameterID").toString();

            String jcrq = cementXd.getJcrq();

            defaultUc.setConclusion(cementXd.getSfhg());
            defaultUc.setUcResultValue(cementXd.getSfhg());
            defaultUc.setUcTestValue(cementXd.getPjz());


            //获取标准值
            for (CheckBatchConfig projectInfo : batchConfigList) {
                if (projectInfo.getTestProjectCode() != null && projectInfo.getTestProjectCode().equals(TestProjectEnum.CEMENT_PARAM_XD.getCode())) {
                    defaultUc.setUcUnit(NullUtils.ifNull(projectInfo.getCheckValueUnit()));
                }
            }


            //根据物料信息设置判断配置
            for (TestProjectSpecConfig test : testProjectSpecConfigList) {
                if (TestProjectEnum.CEMENT_PARAM_XD.getCode().equals(test.getTestProjectCode())) {
                    if (experiment.getMaterialsName() != null && experiment.getMaterialsSpecs() != null && experiment.getMaterialsName().equals(test.getMaterialsName()) && experiment.getMaterialsSpecs().equals(test.getMaterialsSpec())) {
                        String json = test.getObjJson();
                        super.setUcStandardValue(defaultUc, json, "xd");
                    }
                }
            }

            //赋值
            super.setDefUc(defaultUc, experiment, "水泥检测室", sampleNo, jcrq, detail);

            defaultUc.setUcParameterID(parameterID);//项目id

            //新增或修改DataDefaultUc
            super.insertOrUpdateDataDefaultUc(sampleNo, parameterID, defaultUc);

        }
    }

    @Override
    public LaboratoryDownloadVo processDownload(String sampleNo, Experiment experiment, ExperimentDetail detail, Map<String, String> parameterMap, String samId, List<TestProjectInfo> testProjectInfoList) {
        log.info("开始下载协会数据到品控：【水泥-{}】", testProjectEnum.getName());
        JSONObject objJson = detail.getObjJson();
        CementXd cementXd = JsonUtils.getObject(objJson, CementXd.class);
        if (cementXd == null) {
            log.info("【水泥-{}】数据为空，跳过下载！objJson：{}", testProjectEnum.getName(), objJson);
            return null;
        }

        //根据样品编码查询水泥细度
        DataSnXd data = cementLaboratoryMapper.findDATA_JGCL_SN_XD_SXFBySampleNo(sampleNo);

        if (data == null) {
            log.info("根据样品编码查询协会水泥细度信息为空，跳过下载！sampleNo：{}", sampleNo);
            return null;
        }

        if (data.getS11() != null) {
            cementXd.setPjz(data.getS11());
        }
        if (data.getS10() != null) {
            cementXd.setXzxs(data.getS10());
        }
        if (data.getFangKongShaiGuiGe() != null) {
            cementXd.setFksgg(data.getFangKongShaiGuiGe());
        }
        if (data.getConclusion() != null) {
            cementXd.setSfhg(data.getConclusion());
        }
        if (data.getDetectonDate() != null) {
            Date detectonDate = data.getDetectonDate();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String strDate = sdf.format(detectonDate);
            cementXd.setJcrq(strDate);
        }

        List<CementXd.Fysff> fysff = cementXd.getFysff();

        int con = 1;
        if (fysff != null) {
            for (CementXd.Fysff fy : fysff) {
                if (con == 1) {
                    if (data.getS1() != null) {
                        fy.setClz(data.getS1());
                    }
                    if (data.getS2() != null) {
                        fy.setSyl(data.getS2());
                    }
                    if (data.getS3() != null) {
                        fy.setSylv(data.getS3());
                    }
                } else if (con == 2) {
                    if (data.getS4() != null) {
                        fy.setClz(data.getS4());
                    }
                    if (data.getS5() != null) {
                        fy.setSyl(data.getS5());
                    }
                    if (data.getS6() != null) {
                        fy.setSylv(data.getS6());
                    }
                } else if (con == 3) {
                    if (data.getS7() != null) {
                        fy.setClz(data.getS7());
                    }
                    if (data.getS8() != null) {
                        fy.setSyl(data.getS8());
                    }
                    if (data.getS9() != null) {
                        fy.setSylv(data.getS9());
                    }
                }

                con++;
            }
        }


        //对象转json
        JSONObject jsonObject = JsonUtils.beanToObject(cementXd);

        //重新赋值
        detail.setObjJson(jsonObject);

        detail.setEquipment(NullUtils.ifNull(data.getEquipment()));
        detail.setTemperature(NullUtils.ifNull(data.getTemperature()));
        detail.setHumidness(NullUtils.ifNull(data.getHumidity()));
        detail.setExperimentGist(NullUtils.ifNull(data.getDetectonRuleCode()));
        detail.setJudgeGist(NullUtils.ifNull(data.getAccessRuleCode()));


        if (parameterMap != null && parameterMap.get(detail.getTestProjectCode()) != null) {
            detail.setStatus(parameterMap.get(detail.getTestProjectCode()));
        }

        //修改品控试验数据
        experimentDetailMapper.updateByPrimaryKeySelective(detail);

        return new LaboratoryDownloadVo().setEquipment(detail.getEquipment())
                .setJudgeGist(detail.getJudgeGist())
                .setExperimentGist(detail.getExperimentGist())
                .setTemperature(detail.getTemperature())
                .setHumidness(detail.getHumidness());
    }
}
